var stockCheckType = "";
var stockCheckId = "";

/** 表格刷新 */
function gridReload() {
    _grid.trigger("reloadGrid");  //重新加载表格
}

/**
 * 新增盘点任务
 */
function addStockTask() {
    $.get(context_path + "/stockCheck/toStockCheckAddView.do?id=-1").done(function (data) {
        layer.open({
            title: "新增盘点任务",
            type: 1,
            skin: "layui-layer-molv",
            area: ['780px', '620px'],
            shade: 0.6, //遮罩透明度
            moveType: 1, //拖拽风格，0是默认，1是传统拖动
            anim: 2,
            content: data
        });
    });
}

/**
 * 编辑盘点任务
 */
function editStockTask() {
    var checkedNum = getGridCheckedNum("#grid-table", "id");
    if (checkedNum == 0) {
        layer.alert("请选择一条要编辑的盘点任务！");
        return false;
    } else if (checkedNum > 1) {
        layer.alert("只能选择一条盘点任进行编辑操作！");
        return false;
    } else {
        stockCheckId = jQuery("#grid-table").jqGrid('getGridParam', 'selrow');
        $.get(context_path + "/stockCheck/toStockCheckAddView.do?id=" + stockCheckId).done(function (data) {
            layer.open({
                title: "盘点任务编辑",
                type: 1,
                skin: "layui-layer-molv",
                area: ['780px', '620px'],
                shade: 0.6, //遮罩透明度
                moveType: 1, //拖拽风格，0是默认，1是传统拖动
                anim: 2,
                content: data
            });
        });
    }
}

//时间空间初始化
$(".date-picker").datetimepicker({format: 'YYYY-MM-DD HH:mm:ss', useMinutes: true, useSeconds: true});

/**
 * 获取盘点方式
 */
$("#stockCheckMethodNo").select2({
    placeholder: "选择盘点方式",
    minimumInputLength: 0, //至少输入n个字符，才去加载数据
    allowClear: true, //是否允许用户清除文本信息
    delay: 250,
    formatNoMatches: "没有结果",
    formatSearching: "搜索中...",
    formatAjaxError: "加载出错啦！",
    ajax: {
        url: context_path + "/stockCheck/getStockCheckMethodList",
        type: "POST",
        dataType: 'json',
        delay: 250,
        data: function (term, pageNo) { //在查询时向服务器端传输的数据
            term = $.trim(term);
            return {
                queryString: term, //联动查询的字符
                pageSize: 15, //一次性加载的数据条数
                pageNo: pageNo, //页码
                time: new Date()
                //测试
            }
        },
        results: function (data, pageNo) {
            var res = data.result;
            if (res.length > 0) { //如果没有查询到数据，将会返回空串
                var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                return {
                    results: res,
                    more: more
                };
            } else {
                return {
                    results: {}
                };
            }
        },
        cache: true
    }

});

/**
 * 初始化盘点人员下拉列表
 */
$("#stockCheckUserId").select2({
    placeholder: "选择盘点人员",
    minimumInputLength: 0, //至少输入n个字符，才去加载数据
    allowClear: true, //是否允许用户清除文本信息
    delay: 250,
    formatNoMatches: "没有结果",
    formatSearching: "搜索中...",
    formatAjaxError: "加载出错啦！",
    ajax: {
        url: context_path + "/ASNmanage/getSelectUser",
        type: "POST",
        dataType: 'json',
        delay: 250,
        data: function (term, pageNo) { //在查询时向服务器端传输的数据
            term = $.trim(term);
            return {
                queryString: term, //联动查询的字符
                pageSize: 15, //一次性加载的数据条数
                pageNo: pageNo, //页码
                time: new Date()
                //测试
            }
        },
        results: function (data, pageNo) {
            var res = data.result;
            if (res.length > 0) { //如果没有查询到数据，将会返回空串
                var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                return {
                    results: res,
                    more: more
                };
            } else {
                return {
                    results: {}
                };
            }
        },
        cache: true
    }

});

/**
 * 初始化盘点类型下拉列表
 */
$("#stockCheckType").select2({
    placeholder: "选择盘点类型",
    minimumInputLength: 0, //至少输入n个字符，才去加载数据
    allowClear: true, //是否允许用户清除文本信息
    delay: 250,
    formatNoMatches: "没有结果",
    formatSearching: "搜索中...",
    formatAjaxError: "加载出错啦！",
    ajax: {
        url: context_path + "/stockCheck/getStockcheckTypeList",
        type: "POST",
        dataType: 'json',
        delay: 250,
        data: function (term, pageNo) { //在查询时向服务器端传输的数据
            term = $.trim(term);
            return {
                queryString: term, //联动查询的字符
                pageSize: 15, //一次性加载的数据条数
                pageNo: pageNo, //页码
                time: new Date()
                //测试
            }
        },
        results: function (data, pageNo) {
            var res = data.result;
            if (res.length > 0) { //如果没有查询到数据，将会返回空串
                var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                return {
                    results: res,
                    more: more
                };
            } else {
                return {
                    results: {}
                };
            }
        },
        cache: true
    }

});


/**
 * 根据盘点类型动态显示盘点内容
 */
$("#stockCheckContent").select2({
    placeholder: "选择盘点内容",
    minimumInputLength: 0, //至少输入n个字符，才去加载数据
    allowClear: true, //是否允许用户清除文本信息
    delay: 250,
    formatNoMatches: "没有结果",
    formatSearching: "搜索中...",
    formatAjaxError: "加载出错啦！",
    multiple: true,
    ajax: {
        url: context_path + "/stockCheck/getStockcheckContentList",
        type: "POST",
        dataType: 'json',
        delay: 250,
        data: function (term, pageNo) { //在查询时向服务器端传输的数据
            term = $.trim(term);
            return {
                queryString: term, //联动查询的字符
                pageSize: 15, //一次性加载的数据条数
                pageNo: pageNo, //页码
                time: new Date(),
                stockCheckType:$("#stockCheckType").val()
                //测试
            }
        },
        results: function (data, pageNo) {
            var res = data.result;
            if (res.length > 0) { //如果没有查询到数据，将会返回空串
                var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                return {
                    results: res,
                    more: more
                };
            } else {
                return {
                    results: {}
                };
            }
        },
        cache: true
    }

});

$('#stockCheckContent').on("change", function (e) {
    var datas = $("#stockCheckContent").select2("val");
    selectData = datas;
    var selectSize = datas.length;
    if (selectSize > 1) {
        var $tags = $("#s2id_stockCheckContent .select2-choices");   //
        var $choicelist = $tags.find(".select2-search-choice");
        var $clonedChoice = $choicelist[0];
        $tags.children(".select2-search-choice").remove();
        $tags.prepend($clonedChoice);
        $tags.find(".select2-search-choice").find("div").html(selectSize + "个被选中");
        $tags.find(".select2-search-choice").find("a").removeAttr("tabindex");
        $tags.find(".select2-search-choice").find("a").attr("href", "#");
        $tags.find(".select2-search-choice").find("a").attr("onclick", "removeChoice();");
    }
    //执行select的查询方法
    $("#materialInfor").select2("search", selectParam);
});

/**
 * 根据
 */
$("#stockCheckTypeNo").on("change", function () {
    stockCheckType = this.value;
});


/**
 * 盘点任务新增表单验证
 */
$("#stockCheckForm").validate({
    ignore: "",
    rules: {
        "stockCheckTypeName": {
            required: true,
        },
        "stockCheckMethodNo": {
            required: true,
        },
        "stockCheckTime": {
            required: true,
        },
        "stockCheckUserId": {
            required: true,
        },
        "stockCheckContent": {
            required: true,
        }
    },
    messages: {
        "stockCheckTypeName": {
            required: "盘点类型必选!",
        },
        "stockCheckMethodNo": {
            required: "盘点方式必选!",
        },
        "stockCheckTime": {
            required: "盘点时间必填!",
        },
        "stockCheckUserId": {
            required: "盘点人员必选!",
        },
        "stockCheckContent": {
            required: "盘点内容必填!",
        }
    },
    errorClass: "help-inline",
    errorElement: "span",
    highlight:function(element, errorClass, validClass) {
        $(element).parents('.control-group').addClass('error');
    },
    unhighlight: function(element, errorClass, validClass) {
        $(element).parents('.control-group').removeClass('error');
    }
});
/**
 * 盘点任务新增表单验证
 */
$("#stockCheckForm").validate({
    ignore: "",
    rules: {
        "stockCheckMethodName": {
            required: true,
        },
        "stockCheckTime": {
            required: true,
        },
        "stockCheckUserName": {
            required: true,
        }
    },
    messages: {
        "stockCheckMethodName": {
            required: "盘点方式必选!",
        },
        "stockCheckTime": {
            required: "盘点时间必填!",
        },
        "stockCheckUserName": {
            required: "盘点人员必选!",
        }
    },
    errorPlacement: function (error, element) {
        layer.msg(error.html(), {icon: 5});
    }
});

/**
 * 保存盘点任务
 */
$("#formSave").click(function () {
    var bean = $("#stockCheckForm").serialize();
    if ($('#stockCheckForm').valid()) {
        saveOrUpdateStockCheck(bean);
    }
});

/**
 * 保存修改盘点任务
 * @param bean 盘点信息
 */
function saveOrUpdateStockCheck(bean) {
    $.ajax({
        url: context_path + "/stockCheck/saveOrUpdateStockCheck",
        type: "post",
        data: bean,
        dataType: "JSON",
        success: function (data) {
            if (data.result) {
                $("#stockCheckNumber").val(data.stockCheckNo);
                $("#stockCheckId").val(data.id);
                $("#stockCheckLoation").val(data.stockCheckLoation);
                stockCheckId = data.id;
                gridReload();
                $("#grid-table-c").jqGrid('setGridParam',
                    {
                        url: context_path + '/stockCheck/stockCheckDetailList?stockCheckId=' + stockCheckId,
                        postData: {queryJsonString: ""} //发送数据  :选中的节点
                    }).trigger("reloadGrid");
                layer.msg("操作成功！", {icon: 1, time: 1200});
            } else {
                layer.msg(data.message, {icon: 2, time: 1200});
            }
        }
    });
}

/**
 * 删除盘点任务
 */
function deleteStockCheck() {
    var checkedNum = getGridCheckedNum("#grid-table", "id");  //选中的数量
    if (checkedNum == 0) {
        layer.alert("请至少选择一条要删除的盘点任务！");
    } else {
        //从数据库中删除选中的入库单，并刷新入库单表格
        var ids = jQuery("#grid-table").jqGrid('getGridParam', 'selarrrow');
        //弹出确认窗口
        layer.confirm("确定删除选中的盘点任务？", function () {
            $.ajax({
                type: "POST",
                url: context_path + "/stockCheck/deleteStockCheck?stockCheckIds=" + ids,
                dataType: 'json',
                cache: false,
                success: function (data) {
                    layer.closeAll();
                    if (data.message.length==0) {
                        layer.msg("盘点任务删除成功！", {icon: 1, time: 1000});
                    } else {
                        layer.alert(data.message, {icon: 2, time: 1000});
                    }
                    _grid.trigger("reloadGrid");  //重新加载表格
                }
            });
        });
    }
}

/**
 * 提交盘点任务
 */
function confirmStockCheck() {
    layer.confirm("确定提交盘点任务？", function () {
        $.ajax({
            type: "POST",
            url: context_path + "/stockCheck/confirmStockCheck?stockCheckIds=" + $("#stockCheckId").val(),
            dataType: 'json',
            cache: false,
            success: function (data) {
                layer.closeAll();
                if (data.result) {
                    layer.msg(data.message, {icon: 1, time: 1000});
                } else {
                    layer.alert(data.message, {icon: 2, time: 1000});
                }
                _grid.trigger("reloadGrid");  //重新加载表格
            }
        });
    });
}

/**
 * 审核盘点任务
 */
function auditStockCheck() {
    layer.confirm("确定审核的盘点任务？", function () {
        $.ajax({
            type: "POST",
            url: context_path + "/stockCheck/auditStockCheck?stockCheckIds=" + $("#stockCheckId").val(),
            dataType: 'json',
            cache: false,
            success: function (data) {
                layer.closeAll();
                if (data.result) {
                    layer.msg(data.message, {icon: 1, time: 1000});
                } else {
                    layer.alert(data.message, {icon: 2, time: 1000});
                }
                _grid.trigger("reloadGrid");  //重新加载表格
            }
        });
    })
}

//删除货架详情
function delStockCheckDetail() {
    var checkedNum = getGridCheckedNum("#grid-table-c", "id");  //选中的数量
    if (checkedNum == 0) {
        layer.alert("请至少选择一条要删除的盘点任务详情！");
    } else {
        //从数据库中删除选中的盘点任务，并刷新盘点任务表格
        var stockCheckDetailIds = jQuery("#grid-table-c").jqGrid('getGridParam', 'selarrrow');
        //弹出确认窗口
        layer.confirm("确定删除选中的盘点任务详情？", function () {
            $.ajax({
                url: context_path + '/stockCheck/deleteStockCheckDetail?stockCheckDetailIds='+stockCheckDetailIds,
                type: "POST",
                data: {id: $("#stockCheckId").val()},
                dataType: "JSON",
                success: function (data) {
                    if (data.result) {
                        layer.msg("盘点任务详情删除成功！", {icon: 1, time: 1000});
                        //重新加载详情表格
                        $("#grid-table-c").jqGrid('setGridParam',
                            {
                                postData: {stockCheckId: $("#stockCheckId").val()} //发送数据  :选中的节点
                            }
                        ).trigger("reloadGrid");
                    }
                    else {
                        layer.alert(data.message, {icon: 2, time: 1000});
                    }
                }
            });
        });
    }
}

/**
 * 盘点单打印
 * @returns {boolean}
 */
function printStockCheck(){
    var checkedNum = getGridCheckedNum("#grid-table", "id");
    var id="";
    if (checkedNum == 0) {
        layer.alert("请选择要打印的盘点单据！");
        return false;
    }else{
        id = jQuery("#grid-table").jqGrid('getGridParam', 'selarrrow');
    }
    var url = context_path + "/stockCheck/printStockCheck?stockCheckIds=" + id;
    window.open(url);
}

/*盘点任务导出*/
function excelStockCheck(){
    var selectid = jQuery("#grid-table").jqGrid('getGridParam', 'selarrrow');
    $("#ids").val(selectid);
    $("#exportStockCheckForm").submit();
}


